#import <stdio.h>
#import <stdlib.h>
#import <appkit/NXBitmapImageRep.h>
#import <streams/streams.h>
#import "kludge.h"

static int				aC;
static int				w, h;
static id				tmpImage;
static unsigned char	*data[5];
	

NXStream *pcx_openr(char *name)
{
	NXStream		*tFile;
	FILE			*myFile;
	
	myFile = fopen(name, "r");
	if (myFile) {
		tFile = NXOpenFile(fileno(myFile), NX_READONLY);
		if (tFile) {
			return tFile;
		}
	}

	fprintf(stderr, "Unable to open %s\n", name);

	return NULL;
}

id pcx_allocarray(int width, int height)
{
	tmpImage = [[NXBitmapImageRep alloc] initData: NULL
					pixelsWide: 		width
					pixelsHigh:		height
					bitsPerSample:	8
					samplesPerPixel:	3
					hasAlpha:		NO
					isPlanar:			YES
					colorSpace:		NX_RGBColorSpace
					bytesPerRow:		0
					bitsPerPixel:		0];
	w = width;
	h = height;
	[tmpImage getDataPlanes: data];
	return tmpImage;
}

void pcx_init(int argc, char *argv[])
{
	aC = argc;
}

void pcx_usage(char *mes)
{
	fprintf(stderr, "%s\n", mes);
	exit(1);
}

id pcx_close(NXStream *file)
{
	return tmpImage;

//	NXStream	*myStream;
//	FILE		*myFile;
	
//	myFile = fopen("out.tiff", "w");
//	myStream = NXOpenFile(fileno(myFile), NX_WRITEONLY);
//	[tmpImage writeTIFF: myStream];
//	NXClose(myStream);
//	fclose(myFile);

//	NXClose(file);
}

void pcx_error(char *err)
{
	fprintf(stderr, "%s\n", err);
	exit(1);
}

void PCX_ASSIGN(int x, int y, unsigned char r, unsigned char g, unsigned char b)
{
//	if ((x == 0) && !(y % 10)) fprintf(stderr, "%d,%d\n", x, y);
	data[0][y * w + x] = r; 
	data[1][y * w + x] = g; 
	data[2][y * w + x] = b; 
}
